package com.tripspins.app;


import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;


import com.tripspins.app.bo.Attachment;
import com.tripspins.app.bo.Pin;
import com.tripspins.app.bo.Trip;
import com.tripspins.app.bo.User;
import com.tripspins.app.dao.AttachmentDAO;
import com.tripspins.app.dao.PinDAO;
import com.tripspins.app.dao.TripDAO;
import com.tripspins.app.dao.UserDAO;
import com.tripspins.app.fragment.ListPinsFragment;
import com.tripspins.app.fragment.ListTripsFragment;
import com.tripspins.app.fragment.MapDetailsPinFragment;
import com.tripspins.app.fragment.MapDetailsTripFragment;
import com.tripspins.app.helper.ConstantsHelper;
import com.tripspins.app.helper.DbHelper;
import com.tripspins.app.helper.FileHelper;
import com.tripspins.app.helper.MenuHelper;
import com.tripspins.app.helper.TRIP_STATUS;
import com.tripspins.app.interfaces.OnFragmentInteractionListener;

import java.util.ArrayList;


public class MainActivity
        extends FragmentActivity
        implements SharedPreferences.OnSharedPreferenceChangeListener,
        OnFragmentInteractionListener{

    private static final String LIST_TRIPS_FRAG = "list_trips";
    TripDAO tripDao;
    UserDAO userDao;
    PinDAO pinDao;
    ArrayList<Trip> trips;
    boolean isOnTheRoad;
    boolean isAuthenticated;
    DbHelper dbHelper;
    SharedPreferences settings;
    SQLiteDatabase database;
    User loggedUser;

    //Fragments management
    FragmentManager fragmentManager;
    FragmentTransaction fragmentTransaction;
    MapDetailsTripFragment mapDetailsTripFragment;
    //Fragments
    ListTripsFragment listTripsFragment;
    private FinishTripActivity finishFragment;
    private AttachmentDAO attachmentDAO;
    private MapDetailsPinFragment mapDetailsPinFragment;
    private ListPinsFragment listPinsFragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fragmentManager = getSupportFragmentManager();
        dbHelper = new DbHelper(this);
        database =  dbHelper.getWritableDatabase();
        userDao = new UserDAO(database);
        tripDao = new TripDAO(database);
        loggedUser = userDao.getLoggedUser();
        isOnTheRoad = tripDao.isOnTheRoad();
        isAuthenticated = loggedUser != null;

        if(fragmentManager.getFragments() == null) {
            showListTripsFragment();
            MenuHelper.loadMenu(this, isOnTheRoad, isAuthenticated);
        }
        settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    }
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(fragmentManager.getFragments().size() <= 1)
            reloadListTrips();
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

        /*if(key.equals(ConstantsHelper.PREFERENCES_BOOL_MONITOR))
        {
//
//            Preference connectionPref = findPreference(key);
            //kill process
        }*/

    }


    private void showListTripsFragment() {
        if(database==null || !database.isOpen()){
            dbHelper = new DbHelper(this);
            database = dbHelper.getWritableDatabase();
        }
        tripDao = new TripDAO(database);
        if(isAuthenticated) {
            trips = tripDao.getTripsByUser(loggedUser.getId());
        } else {
            trips = tripDao.getAnonymousTrips();
        }
        listTripsFragment = ListTripsFragment.newInstance(trips, tripDao.isOnTheRoad());
        database.close();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.main_holder, listTripsFragment,LIST_TRIPS_FRAG);
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        fragmentTransaction.commit();
    }

    private void killListTripsFragment() {
        Fragment fragment = fragmentManager.findFragmentByTag(LIST_TRIPS_FRAG);
        if(fragment != null)
            fragmentManager.beginTransaction().remove(fragment).commit();
    }

    private void showNewTripActivity() {
        FileHelper fileHelper = new FileHelper(this);
        fileHelper.cleanTempFolders();
        Intent intent = new Intent(this, NewTripActivity.class);
        startActivity(intent);

    }

    private void showMapDetailFragment(Trip trip) {

        mapDetailsTripFragment = MapDetailsTripFragment.newInstance(trip);
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.main_holder, mapDetailsTripFragment);
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

    }

    @Override
    public void newTrip() {
        showNewTripActivity();
    }

    @Override
    public void viewTrip(long tripId) {
        if(!database.isOpen())
            database = dbHelper.getWritableDatabase();
        tripDao = new TripDAO(database);
        showMapDetailFragment(tripDao.getTrip(tripId));
    }

    @Override
    public void saveNewTrip(Trip trip) {
        if(loggedUser != null)
            trip.setUserId(loggedUser.getId());
        if(!database.isOpen())
            database = dbHelper.getWritableDatabase();
        tripDao = new TripDAO(database);
        ArrayList<Attachment> tempAttachments = trip.getPinStart().getAttachments();
        trip.setId(tripDao.persist(trip));
        trip = tripDao.getTrip();
        trip.getPinStart().setAttachments(tempAttachments);
        saveTempFiles(trip.getId(), trip.getPinStart());
        attachmentDAO = new AttachmentDAO(database);
        attachmentDAO.persist(trip.getPinStart().getId(), tempAttachments);
        killListTripsFragment();
        showListTripsFragment();
    }

    @Override
    public void viewTripAsList(Trip trip) {
        listPinsFragment = ListPinsFragment.newInstance(trip);
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.main_holder,listPinsFragment);
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_new_pin:
                showNewPinActivity();
                break;
            case R.id.menu_new_trip:
                showNewTripActivity();
            /*case R.id.menu_settings:
                final Intent intentSettingsActivity = new Intent(this,SettingsActivity.class);
                startActivity(intentSettingsActivity);
            */
                break;
            case R.id.menu_finish:
                final Intent intentFinishTripActivity = new Intent(this,FinishTripActivity.class);
                startActivity(intentFinishTripActivity );

                break;
                 /*case R.id.menu_login_fb:
                final Intent intentLoginActivity = new Intent(this,LoginActivity.class);
                startActivity(intentLoginActivity);
                */
            default:
                return super.onOptionsItemSelected(item);
        }
        return true;
    }

    @Override
    public boolean menuItemClicked(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    //@Override
    public void newPin() {
        showNewPinActivity();
    }

    private void showNewPinActivity() {
        FileHelper fileHelper = new FileHelper(this);
        fileHelper.cleanTempFolders();
        Intent intent = new Intent(this, NewPinActivity.class);
        intent.putExtra("IS_ON_THE_ROAD",isOnTheRoad);
        startActivity(intent);
    }

    //@Override
    public void saveNewPin(Pin newPin) {
        if(isOnTheRoad) {
            if (!database.isOpen())
                database = dbHelper.getWritableDatabase();
            tripDao = new TripDAO(database);
            pinDao = new PinDAO(database);
            Trip trip = tripDao.getTrip();
            newPin.setId(pinDao.persist(trip.getId(), newPin));
            saveTempFiles(trip.getId(), newPin);
            attachmentDAO = new AttachmentDAO(database);
            attachmentDAO.persist(newPin.getId(), newPin.getAttachments());

        }
        killListTripsFragment();
        showListTripsFragment();
    }

    @Override
    public void finishTrip() {
        showFinishTripFragment();
    }



    @Override
    public void viewPinOnMap(Pin pin, long tripId) {
        mapDetailsPinFragment = MapDetailsPinFragment.newInstance(pin, tripId);
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.main_holder, mapDetailsPinFragment);
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    @Override
    public void reloadListTrips() {
        killListTripsFragment();
        showListTripsFragment();

    }

    private void saveTempFiles(long tripId, Pin newPin) {
        FileHelper fileHelper = new FileHelper(this);
        fileHelper.persistTempFiles(tripId, newPin.getId());
        for(Attachment att : newPin.getAttachments())
        {
            if(att.getContact()==null)
                att.setPath(fileHelper.getAttachmentsDirectory(tripId,newPin.getId()).getPath() + "/" + att.getFileName());
        }
        fileHelper.cleanTempFolders();

    }

    private void showFinishTripFragment() {
        FileHelper fileHelper = new FileHelper(this);
        fileHelper.cleanTempFolders();
        Intent intent = new Intent(this, FinishTripActivity.class);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
